/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package IFSv2.Forms;

import IFSv2.Models.mdlLogin;
import IFSv2.Operations.clsConnectionProvider;
import IFSv2.Connection.DBConnection;
import IFSv2.Forms.Main.frmMain;
import IFSv2.Operations.clsLogin;
import IFSv2.Util.utilErrorHandler;
import IFSv2.Util.utilSystemPath;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Fulbert
 */
public class frmLogin extends javax.swing.JFrame {

    private boolean clicked = false;
    private final int DEFAULT_WIDTH = 140;
    private final int EXTENDED_WIDTH = 397;

    public frmLogin() {
        
        initComponents();
        
        setIconImage(utilSystemPath.getFormImage(this.getClass().getResource("/IFSv2/Images/timlogo.png")));
        setLocationRelativeTo(null);
        setSize(getWidth(), DEFAULT_WIDTH);
        
        loadCredentials();

    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        loginPanel = new javax.swing.JPanel();
        lblUserName = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        txtUsername = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        lblSQLServer = new javax.swing.JLabel();
        lblDBUsername = new javax.swing.JLabel();
        lblDBPassword = new javax.swing.JLabel();
        cbSQLServer = new javax.swing.JComboBox();
        txtDBUsername = new javax.swing.JTextField();
        lblDBServer = new javax.swing.JLabel();
        txtDBServer = new javax.swing.JTextField();
        lblDBPort = new javax.swing.JLabel();
        txtDBPort = new javax.swing.JTextField();
        lblDatabase = new javax.swing.JLabel();
        btnLogin = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        cbDatabase = new javax.swing.JComboBox();
        cbxSave = new javax.swing.JCheckBox();
        txtPassword = new javax.swing.JPasswordField();
        txtDBPassword = new javax.swing.JPasswordField();
        moreLbl = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TIM Software");
        setResizable(false);

        loginPanel.setBackground(new java.awt.Color(255, 255, 255));
        loginPanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        lblUserName.setText("Username");

        lblPassword.setText("Password");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel3.setText("Login");

        txtUsername.setNextFocusableComponent(txtPassword);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel4.setText("Database");

        lblSQLServer.setText("SQL Server");

        lblDBUsername.setText("DB Username");

        lblDBPassword.setText("DB Password");

        cbSQLServer.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "MSSQL", "MySQL", "ORACLE" }));
        cbSQLServer.setSelectedIndex(0);
        cbSQLServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbSQLServerActionPerformed(evt);
            }
        });

        lblDBServer.setText("DB Server");

        lblDBPort.setText("Port");

        txtDBPort.setEnabled(false);

        lblDatabase.setText("Database");

        btnLogin.setText("Login");
        btnLogin.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnLoginMouseClicked(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelMouseClicked(evt);
            }
        });

        cbDatabase.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                cbDatabaseFocusGained(evt);
            }
        });

        cbxSave.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        cbxSave.setText("Save values");

        txtPassword.setNextFocusableComponent(btnLogin);

        moreLbl.setText("show more↓");
        moreLbl.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                moreLblMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout loginPanelLayout = new javax.swing.GroupLayout(loginPanel);
        loginPanel.setLayout(loginPanelLayout);
        loginPanelLayout.setHorizontalGroup(
            loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loginPanelLayout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(moreLbl)
                    .addGroup(loginPanelLayout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblDBUsername)
                            .addComponent(lblDBPassword)
                            .addComponent(lblDBServer)
                            .addComponent(lblSQLServer)
                            .addComponent(lblDBPort)
                            .addComponent(lblDatabase))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtDBPassword)
                            .addComponent(cbSQLServer, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtDBServer)
                            .addComponent(txtDBPort, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(cbDatabase, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(loginPanelLayout.createSequentialGroup()
                                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cbxSave)
                                    .addComponent(txtDBUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(loginPanelLayout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(loginPanelLayout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jSeparator1))
                        .addGroup(loginPanelLayout.createSequentialGroup()
                            .addGap(10, 10, 10)
                            .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lblUserName)
                                .addComponent(lblPassword))
                            .addGap(18, 18, 18)
                            .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(txtUsername)
                                .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(18, 18, 18)
                            .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(btnLogin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnCancel, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)))))
                .addContainerGap(28, Short.MAX_VALUE))
        );
        loginPanelLayout.setVerticalGroup(
            loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loginPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUserName)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnLogin))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPassword)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCancel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(moreLbl)
                .addGap(7, 7, 7)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDBUsername)
                    .addComponent(txtDBUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDBPassword)
                    .addComponent(txtDBPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSQLServer)
                    .addComponent(cbSQLServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDBServer)
                    .addComponent(txtDBServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDBPort)
                    .addComponent(txtDBPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDatabase)
                    .addComponent(cbDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(cbxSave)
                .addGap(25, 25, 25))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(loginPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(loginPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelMouseClicked
        System.exit(0);
    }//GEN-LAST:event_btnCancelMouseClicked

    private void cbSQLServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbSQLServerActionPerformed
        if (cbSQLServer.getSelectedIndex() == 0) {//Microsoft Sql Server
            txtDBPort.setText(null);
            txtDBPort.setEnabled(false);
        } else if (cbSQLServer.getSelectedIndex() == 1) {//Mysql
            txtDBPort.setEnabled(true);
        } else if (cbSQLServer.getSelectedIndex() == 2) {//Oracle
            txtDBPort.setEnabled(true);
        }
    }//GEN-LAST:event_cbSQLServerActionPerformed

    private void btnLoginMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnLoginMouseClicked
        login();
    }//GEN-LAST:event_btnLoginMouseClicked

    private void login(){
        
        mdlLogin.database = cbDatabase.getSelectedItem().toString();
        mdlLogin.saved = cbxSave.isSelected();
        mdlLogin.username = txtUsername.getText();
        mdlLogin.password = txtPassword.getText();
        
        saveCredentials(cbxSave.isSelected());

        //shortcut
        
        loadMainPanel();

//        clsLogin login = new clsLogin();
//        String username = txtUsername.getText();
//        String password = txtPassword.getText();
//        
//        if (login.login(username, password)){
//            loadMainPanel();
//        }else{
//            utilErrorHandler.printError("Login: Incorrect Credentials", "LoginForm", "Login");
//        }

    }

    private void loadMainPanel(){
        frmMain mainForm = new frmMain();
        mainForm.show();
        this.dispose();
    }

    private void saveCredentials(boolean saveCredential){
                
        Preferences userPref = Preferences.userRoot();
        if(saveCredential){
            userPref.put("usr",mdlLogin.dbUsername);
            userPref.put("pass",mdlLogin.dbPassword);
            userPref.put("sqlsrvr", mdlLogin.sqlServer);
            userPref.put("dbsrvr", mdlLogin.dbServer);
            userPref.put("port", mdlLogin.dbPort);
            userPref.put("db", mdlLogin.database);
            userPref.put("sel", (mdlLogin.saved) ? "1" : "0");
        }else{
            userPref.remove("usr");
            userPref.remove("pass");
            userPref.remove("sqlsrvr");
            userPref.remove("dbsrvr");
            userPref.remove("port");
            userPref.remove("db");
            userPref.remove("sel");
        }
        
    }

    private void loadCredentials(){
        Preferences userPref = Preferences.userRoot();
        mdlLogin.dbUsername = userPref.get("usr", null);
        mdlLogin.dbPassword = userPref.get("pass", null);
        mdlLogin.sqlServer = userPref.get("sqlsrvr",null);
        mdlLogin.dbServer = userPref.get("dbsrvr",null);
        mdlLogin.dbPort = userPref.get("port", null);
        mdlLogin.database = userPref.get("db",null);
        mdlLogin.saved = (userPref.get("sel","0").equals("1")) ? true : false;
        
        txtDBUsername.setText(mdlLogin.dbUsername);
        txtDBPassword.setText(mdlLogin.dbPassword);
        cbSQLServer.setSelectedItem(mdlLogin.sqlServer);
        txtDBServer.setText(mdlLogin.dbServer);
        txtDBPort.setText(mdlLogin.dbPort);
        cbxSave.setSelected(mdlLogin.saved);
        loadcbDatabase();
        cbDatabase.setSelectedItem(mdlLogin.database);
    }

    private void loadcbDatabase(){
        
        if(mdlLogin.dbUsername == null || mdlLogin.dbPassword == null || "NULL".equals(mdlLogin.sqlServer)){
            return;
        }
        cbDatabase.removeAllItems();
       
        clsConnectionProvider connProvider = new clsConnectionProvider();
        if(connProvider.dbConnect()){
            List<String> dbList = connProvider.getDatabaseList();   
            for(String dbItem : dbList){
                cbDatabase.addItem(dbItem);
            }
        }
    }
    
    private void getDBList(){

        mdlLogin.dbUsername = txtDBUsername.getText();
        mdlLogin.dbPassword = txtDBPassword.getText();       
        mdlLogin.sqlServer = (cbSQLServer.getSelectedIndex() == -1) ? "NULL" : cbSQLServer.getSelectedItem().toString();
        mdlLogin.dbServer = txtDBServer.getText();
        mdlLogin.dbPort = txtDBPort.getText();
        
        loadcbDatabase();

    }
    
    private void moreLblMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_moreLblMouseClicked
        showDBOptions();
    }//GEN-LAST:event_moreLblMouseClicked

    private void loginBtnKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_loginBtnKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_SPACE){
            login();
        }
    }//GEN-LAST:event_loginBtnKeyPressed

    private void cbDatabaseFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cbDatabaseFocusGained
        getDBList();
    }//GEN-LAST:event_cbDatabaseFocusGained
    
    private void showDBOptions(){
        
        clicked = (clicked) ? false : true;
        
        if(clicked){
            this.setSize(this.getWidth(), EXTENDED_WIDTH);
            moreLbl.setText("show less↑");
        }else{
            this.setSize(this.getWidth(), DEFAULT_WIDTH);
            moreLbl.setText("show more↓");
        }
    }
    /*
    public static void main(String args[]) {


        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new frmLogin().setVisible(true);
            }
        });
    }
    * 
    */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnLogin;
    private javax.swing.JComboBox cbDatabase;
    private javax.swing.JComboBox cbSQLServer;
    private javax.swing.JCheckBox cbxSave;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblDBPassword;
    private javax.swing.JLabel lblDBPort;
    private javax.swing.JLabel lblDBServer;
    private javax.swing.JLabel lblDBUsername;
    private javax.swing.JLabel lblDatabase;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblSQLServer;
    private javax.swing.JLabel lblUserName;
    private javax.swing.JPanel loginPanel;
    private javax.swing.JLabel moreLbl;
    private javax.swing.JPasswordField txtDBPassword;
    private javax.swing.JTextField txtDBPort;
    private javax.swing.JTextField txtDBServer;
    private javax.swing.JTextField txtDBUsername;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables
}
